<template>
  <div>
    <Drawer
      ref="modal"
      :title="$t('newDevices.openDoorPermissions')"
      :width="1000"
      :value="show"
      :beforeClose="$_modal_decideIfClose"
      @on-close="show=false"
    >
      <Form
        ref="form"
        :labelWidth="140"
        :model="formData"
        :rules="formRule"
      >
       <FormItem prop="recordTypes" :label="$t('newDevices.site')">
          <Cascader style="width: 300px" :data="formData.recordTypes" v-model="formData.recordType" disabled
            @on-change="handleChange1"
            change-on-select>
          </Cascader>
          <!-- <div style="line-height:20px;margin-top:8px">{{$t('newDevices.siteParentTip')}}</div> -->
        </FormItem>
        <FormItem prop="dateTime" :label="$t('newDevices.dateTime')">
          <RadioGroup v-model="formData.dateTime">
            <!-- <Radio label="1">
              <span>{{ $t("newDevices.longTime") }}</span>
            </Radio> -->
            <!-- <Radio label="0" style="display:block;margin-top:10px"> -->
            <Radio label="0">
              <span>{{ $t("newDevices.dateTime1") }}</span>
              <DatePicker
                class="date-widget"
                v-model="selectDate"
                type="datetimerange"
                :placeholder="$t('emailSetting.BodyTemAnimalTimeScope')"
                style="margin-left:20px;width:320px"
              />
           
            </Radio>
          </RadioGroup>
        </FormItem>
        <FormItem prop="type" :label="$t('newDevices.type')">
          <RadioGroup v-model="formData.type" @on-change="changeType">
            <Radio label="0" style="display:block">
              <span style="margin-right:50px;">{{ $t("newDevices.dayNum") }}</span>
              <!-- v-show="formData.type==0" -->
              <!-- @on-change="changeDayNumType" -->
              <RadioGroup v-show="formData.type==0" v-model="formData.dayNumType"  style="display:inline-block;margin-left:0px">
                <Radio label="0">
                  <span style="margin-right:10px;">{{ $t("newDevices.unlimited") }}</span>
                </Radio>
                <Radio label="1">
                  <span style="margin-right:10px;">{{ $t("newDevices.fixedTimes") }}</span>
                  <InputNumber v-show="formData.dayNumType==1"
                    v-model="formData.dayNum"
                    :min="0" :max="100000"
                    :step="1"
                    :style="{ width: '100px'}"
                  />
                </Radio>
              </RadioGroup>
              
            </Radio> 
            <Radio label="1" style="display:block;">
              <span >{{ $t("newDevices.dayTime") }}</span>
              <RadioGroup v-show="formData.type==1" v-model="formData.dayTimeType" style="display:block;margin-left:30px">
                <Radio label="0" style="display:block;">
                  <span style="margin-right:10px;">{{ $t("newDevices.unlimited") }}</span>
                </Radio>
                <Radio label="1" style="display:block;">
                  <span style="margin-right:10px;">{{ $t("newDevices.specifyTime") }}</span>
                  <div  v-show="formData.dayTimeType==1">
                    <div v-for="(item,index) in formData.dayDatas" :key="index">
                      <TimePicker class="date-widget"  format="HH:mm" :clearable="false" placement="bottom-end" v-model="item.atime" :placeholder="$t('emailSetting.BodyTemAnimalTimeScope')" style="margin-left:30px;width: 120px;display:inline-block;margin-bottom:10px"></TimePicker>
                      <TimePicker class="date-widget"  format="HH:mm" :clearable="false" placement="bottom-end" v-model="item.btime" :placeholder="$t('emailSetting.BodyTemAnimalTimeScope')" style="margin-left:30px;width: 120px;display:inline-block;margin-bottom:10px"></TimePicker>
                      <Button @click="Sub(index)" v-show="index!='0'" style="margin-left:20px">{{$t('emailSetting.Del')}}</Button>
                      <div v-show="showDayTimeTip==index" style="margin-left:32px;color:#ed4014">{{$t('newDevices.dayTime')+$t('visitorsIndex.visitorsInputTime')}}</div>
                    </div>   
                    
                    <div >
                      <Button @click="Add()" style="margin-left:30px">{{$t('emailSetting.Add')}}</Button>
                    </div>  
                  </div>  
                </Radio>
              </RadioGroup>
              <!-- <div  v-show="formData.type==1">
                <div v-for="(item,index) in formData.dayDatas" :key="index">
                  <TimePicker class="date-widget"  format="HH:mm" :clearable="false" placement="bottom-end" v-model="item.atime" :placeholder="$t('emailSetting.BodyTemAnimalTimeScope')" style="margin-left:30px;width: 120px;display:inline-block;margin-bottom:10px"></TimePicker>
                  <TimePicker class="date-widget"  format="HH:mm" :clearable="false" placement="bottom-end" v-model="item.btime" :placeholder="$t('emailSetting.BodyTemAnimalTimeScope')" style="margin-left:30px;width: 120px;display:inline-block;margin-bottom:10px"></TimePicker>
                  <Button @click="Sub(index)" v-show="index!='0'" style="margin-left:20px">{{$t('emailSetting.Del')}}</Button>
                  <div v-show="showDayTimeTip==index" style="margin-left:32px;color:#ed4014">{{$t('newDevices.dayTime')+$t('visitorsIndex.visitorsInputTime')}}</div>
                </div>   
                
                <div >
                  <Button @click="Add()" style="margin-left:30px">{{$t('emailSetting.Add')}}</Button>
                </div>  
              </div>   -->
              <!-- <Form
                ref="form1"
                :labelWidth="140"
                :model="formData.dayDatas"
                :rules="formRule"
                v-show="formData.type==1"
              >  
                <FormItem v-for="(item,index) in formData.dayDatas" :key="index">
                  <TimePicker class="date-widget"  format="HH:mm" :clearable="false" placement="bottom-end" v-model="item.atime" :placeholder="$t('emailSetting.BodyTemAnimalTimeScope')" style="margin-left:30px;width: 120px;display:inline-block;margin-bottom:10px"></TimePicker>
                  <TimePicker class="date-widget"  format="HH:mm" :clearable="false" placement="bottom-end" v-model="item.btime" :placeholder="$t('emailSetting.BodyTemAnimalTimeScope')" style="margin-left:30px;width: 120px;display:inline-block;margin-bottom:10px"></TimePicker>
                  
                  <Button @click="Sub(index)" style="margin-left:20px">删除时间段</Button>
                </FormItem>   
                <FormItem >
                  <Button @click="Add(index)" style="margin-left:30px">新增时间段</Button>
                </FormItem>   
              </Form>  -->
            </Radio>
          </RadioGroup>
        </FormItem>
        <FormItem prop="week" :label="$t('newDevices.week')">
          <RadioGroup v-model="formData.weekType">
            <Radio label="0">
              <span>{{ $t("newDevices.weekType") }}</span>
              <CheckboxGroup v-model="formData.week" style="display:inline-block;margin-left:20px">
                  <Checkbox v-for="(item, idx) in formData.weeks" :key="idx" :value="item.id" :label="item.id">{{item.value}}</Checkbox>
              </CheckboxGroup>
            </Radio>
          </RadioGroup>
        </FormItem>
        <FormItem prop="list" :label="$t('newDevices.list')">
          <RadioGroup v-model="formData.list">
            <Radio label="0">
              <span>{{ $t("newDevices.list1") }}</span>
            </Radio>
            <Radio label="1">
              <span>{{ $t("newDevices.list2") }}</span>
            </Radio>
          </RadioGroup>
        </FormItem>
        <FormItem class="glo-btn-group">
          <Button
            type="primary"
            :loading="loading"
            @click="handleSubmit"
          >{{ $t("devicesCreate.devCreateSubmit") }}</Button>
          <Button
            @click="$_modal_close"
          >{{ $t("devicesCreate.devCreateCancel") }}</Button>
        </FormItem>
      </Form>
    </Drawer>
  </div>
</template>

<script>
import {
  // create,
  // update,
  getOpenAccess,
  updateOpenAccess,
  getSite,
  getParentArea
} from '@/api/newDevices.js'
import modalMixin from '@/utils/mixins/modalMixin.js'
import moment from 'moment'
//自定义规则校验邮箱输 入
var validateEmail = (rule, value, callback) => {
  
};

export default {
  mixins: [
    modalMixin,
  ],

  props: {
    editType: {
      type: String,
      default: 'create',
    },
    editItem: Object,
  },
  data () {
    return {
      show: false,
      loading: false,
      // roles: [],
      formData: {
        recordTypes: [],
        recordType: [],
        dateTime:'0',
        type: '0',
        aDate:'',//起点日期
        bDate:'',//结束日期
        dayNum:1,
        passNum:'',//接口返回的每日通过次数
        dayNumType:'0',
        dayTimeType:'1',
        // aTime:'',//起点时间
        // bTime:'',//结束时间
        weekType:'0',
        week: [],
        weeks: [
          { id:'1',value:this.$t('newDevices.week1') },
          { id:'2',value:this.$t('newDevices.week2') },
          { id:'3',value:this.$t('newDevices.week3') },
          { id:'4',value:this.$t('newDevices.week4') },
          { id:'5',value:this.$t('newDevices.week5') },
          { id:'6',value:this.$t('newDevices.week6') },
          { id:'7',value:this.$t('newDevices.week7') },
        ],
        dayDatas:[
          { atime:'00:00',btime:'23:59' },
        ],
        list: '0',
      },
        
      // numType:'0',
      // numTypes: [
      //   { name: this.$t('newDevices.unlimited'), value: '0' },
      //   { name: this.$t('AccessIndex.AccessOpenDoorFace'), value: '1' },
      //   { name: this.$t('AccessIndex.AccessOpenDoorPass'), value: '2' },
      //   { name: this.$t('AccessIndex.AccessOpenDoorApp'), value: '3' },
      // ],
      selectDate: [],
      // selectTime: ['00:00','24:00'],
      // selectTime1: ['00:00','24:00'],
      formRule: {
        // name: { required: true, message: this.$t('emailSetting.Noempty'), trigger: 'blur' },
        // contact: { required: true, message: this.$t('emailSetting.Noempty'), trigger: 'blur' },
        // contact: {required: true,validator: (rule, value, callback) => {
        //   var reg = /^1[3456789]\d{9}$/
        //   if (this.formData.contact) {
        //     if (!reg.test(this.formData.contact)) {
        //       return callback(new Error(this.$t('companyManagement.phoneTip')))
        //     } else {
        //       return callback()
        //     }
        //   } else {
        //     return callback(new Error(this.$t('emailSetting.Noempty')))
        //   }
        // }, trigger: 'blur' },
      },
      showDayTimeTip:'null',
    }
  },
  

  created() {
    
    if(this.editType == 'update'){
      this.getSiteList()
      // this.getData()
      console.log('dayNum',this.dayNum)
    }  
    this.getDetail()
    this.getParent()
    // this.show=true;
    // console.log('this.editItem')
    // console.log(this.editItem)
  },
  mounted () {
    // this.show=true;
  },

  methods: {
    async handleSubmit () {
      const ifVlid = await this.$refs.form.validate()
      if (ifVlid && this.editType === 'update') {
        
        this.handleUpdate()
      }else if(ifVlid && this.editType === 'create'){
        this.handleCreate()
      }
    },
    // 获取上级场所
    async getParent(){
      let editItem= JSON.parse(window.sessionStorage.getItem('editItem'))
      let data1={
        id:editItem.id,
        parentId: editItem.parentId,
      }
      const { success ,data} = await getParentArea(data1)
      if (success) {
        setTimeout(() => {
          this.formData.recordType=data.data
        }, 500);
        
      } else {
        this.$Message.error(this.$t('staffIndex.stafferror'))
      }
      if(!this.recordType){
        setTimeout(()=>{
          let arr=[]
          arr.push(this.formData.recordTypes[0].value)
          this.formData.recordType=arr    
        },400)
      }
    },
    // async handleCreate () {
    //   // const formData = this.generateFormData()
    //   // console.log(formData)
    //   const { success, data } = await create(this.formData)
    //   if (success) {
    //     this.$Message.success(this.$t('devicesCreate.devCreateS'))
    //     this.ifUpdateUpper = true
    //     this.$_modal_close()
    //     this.$emit('updata')
    //   } else {
    //     this.$Message.error(data)
    //   }
    // },
    
    async handleUpdate () {
      //自定义有效期期处理
      var startDate = ""
      var endDate = ""
      if (this.selectDate.length) {
        [startDate, endDate] = this.selectDate
        if (moment.isDate(startDate)) {
          startDate = moment(startDate).format('YYYY-MM-DD HH:mm:ss')
        }
        if (moment.isDate(endDate)) {
          endDate = moment(endDate).format('YYYY-MM-DD HH:mm:ss')
        }
      }
      if(startDate>endDate){
        this.$Message.error(this.$t('newDevices.dateTime')+this.$t('visitorsIndex.visitorsInputTime'))
        return
      }
      let startYear=moment(startDate).format('YYYY')
      let endYear=moment(endDate).format('YYYY')
      // console.log('bijiao',startYear,endYear)
      if(endYear-startYear>18){
        this.$Message.error(this.$t('newDevices.dateTimeTip'))
        return
      }
      let passNum='',passTimeSection='',always=''
      //类型
      if(this.formData.type==0){
        passTimeSection=""
        if(this.formData.dayNumType==1){
          passNum=this.formData.dayNum
        }else{
          passNum="-1"
        }
      }else if(this.formData.type==1){
        passNum='-1'
        if(this.formData.dayTimeType==1){
          for (let i = 0; i < this.formData.dayDatas.length; i++) {
            const v = this.formData.dayDatas[i];
            if(v.atime>v.btime){
              // this.$Message.error(this.$t('newDevices.dayTime')+this.$t('visitorsIndex.visitorsInputTime'))
              this.showDayTimeTip=i
              return
            }
            if(i==this.formData.dayDatas.length-1){
              passTimeSection+=v.atime+'~'+v.btime
            }else{
              passTimeSection+=v.atime+'~'+v.btime+','
            }
          }
          always=0
        }else{
          //每日时间不限传0
          passTimeSection=''
          always=1
        }

        
        // this.formData.dayDatas.forEach((v,i)=>{
        //   if(i==this.formData.dayDatas.length-1){
        //     passTimeSection+=v.atime+'~'+v.btime
        //   }else{
        //     passTimeSection+=v.atime+'~'+v.btime+','
        //   }
        // })
      }
      //周期
      let passPeriod=''
      if(this.formData.week.includes('1')){
        passPeriod+='1'
      }else{
        passPeriod+='0'
      }
      if(this.formData.week.includes('2')){
        passPeriod+='1'
      }else{
        passPeriod+='0'
      }
      if(this.formData.week.includes('3')){
        passPeriod+='1'
      }else{
        passPeriod+='0'
      }
      if(this.formData.week.includes('4')){
        passPeriod+='1'
      }else{
        passPeriod+='0'
      }
      if(this.formData.week.includes('5')){
        passPeriod+='1'
      }else{
        passPeriod+='0'
      }
      if(this.formData.week.includes('6')){
        passPeriod+='1'
      }else{
        passPeriod+='0'
      }
      if(this.formData.week.includes('7')){
        passPeriod+='1'
      }else{
        passPeriod+='0'
      }
      let data2={
        mid:this.editItem.mid,
        areaId:window.sessionStorage.getItem('tableId')||'',
        passNum,
        always,
        lastClick:this.formData.type,
        startTime:startDate,
        expireTime:endDate,
        isBlack:this.formData.list,
        passPeriod,
        passTimeSection,
      }
      const { success, data } = await updateOpenAccess(data2)
      if (success) {
        console.log('data',data)
        this.$Message.success(this.$t('devicesCreate.devCreateUpdateS'))
        this.$emit('updata')
      } else {
        this.$Message.error(data)
      }
      this.$_modal_close()
    },
    async getDetail(){
      let res=await getOpenAccess({mid:this.editItem.mid,areaId:window.sessionStorage.getItem('tableId')||'',})
      if(res.data.data){
        
        if(res.data.data.startTime&&res.data.data.expireTime){
          let arr=[]
          arr.push(res.data.data.startTime)
          arr.push(res.data.data.expireTime)
          this.selectDate=arr
        }
        if(res.data.data.isBlack){
          this.formData.list=res.data.data.isBlack+''
        }
        if(res.data.data.passPeriod){
          let da1=res.data.data.passPeriod.toString()
          
          for (let index = 0; index < da1.length; index++) {
            var v = da1[index];
            let idx=index+1+''
            if(v=='1'){
              this.formData.week.push(idx)
            }
            // console.log(v)
          }
          // return
        }
        if(res.data.data.passTimeSection){
          if(res.data.data.passTimeSection==0){
            this.formData.dayTimeType='0'
            return
          }
          // if(res.data.data.passNum=="-1"){
          //   this.formData.type='1'
          // }
          let data1=res.data.data.passTimeSection.split(',');
          let arr12=[]
          data1.forEach(v=>{
            let da=v.split('~');
            let obj={}
            arr12.push({
              atime:da[0],
              btime:da[1],
            })
          })
          this.formData.dayDatas=arr12
          if(this.formData.dayDatas.length>0){
            this.formData.dayTimeType='1'
          }else{
            this.formData.dayTimeType='0'
          }
        }
        
        // if(res.data.data.passNum){
        //   if(res.data.data.passNum=='-1'){
        //     this.formData.dayNum= 1
        //     this.formData.type='0'
        //     this.formData.dayNumType='0'
        //     // this.passNum=res.data.data.passNum
        //   }else{
        //     this.formData.dayNum= res.data.data.passNum
        //     this.formData.type='0'
        //     this.formData.dayNumType='1'
        //   } 
        // }
        
        if(res.data.data.lastClick==1){
          this.formData.type='1'
          if(res.data.data.always==1){
            this.formData.dayTimeType='0'
          }else{
            this.formData.dayTimeType='1'
          }
        }else{
          this.formData.type='0'
          if(res.data.data.passNum=='-1'){
            this.formData.dayNum= 1
            this.formData.dayNumType='0'
          }else{
            this.formData.dayNum= res.data.data.passNum
            this.formData.dayNumType='1'
          }
        }
        // console.log('detail',this.formData)  
      }else{
        // this.$Message.error("查询当前数据失败！")
        console.log("查询当前数据失败！")
      }
      this.show=true;
    },
    handleChange1 (value) {
      // Change时候赋值给recordType  然后关闭级联下拉框可以选中
      this.formData.recordType = value
      console.log('woshi====',this.formData.recordType)
    },
    async getSiteList(){
      const { success ,data} = await getSite()
      if (success) {
        const list=data.data
        let listString = JSON.stringify(list).replace(/"id"/g, '"value"')
        let listStringLabel = listString.replace(/"areaName"/g, '"label"')
        let listStringChildren = listStringLabel.replace(/"children"/g, '"children"')
        var aParse = JSON.parse(listStringChildren)
        // this.recordTypes=data.data 
        function dG(params) {
        params.forEach(v=>{
          if(v.children){
            dG(v.children)
          }else{
            v.children=[]
          }
        })
      }
      dG(aParse)
      if(aParse&&aParse[0].label==="新场所"){
          let arr11=aParse
          arr11[0].label=this.$t('title.newSite')
          this.formData.recordTypes=arr11
        }else{
          this.formData.recordTypes=aParse 
        }
        // this.formData.recordTypes=aParse  
        // setTimeout(()=>{
        //   let arr=[]
        //   arr.push(this.formData.recordTypes[0].value)
        //   this.formData.recordType=arr   
        //   // this.formData.recordType=window.sessionStorage.getItem('areaName')||''   
        // },400)
      } else {
        this.$Message.error(this.$t('staffIndex.stafferror'))
      }
    },
    Add(){
      this.formData.dayDatas.push(
        { atime:'00:00',btime:'23:59' },
      )
    },
    Sub(index){
      if(index==0){
        return
      }
      this.formData.dayDatas.splice(index,1)
    },
    changeType(value){
      // console.log(value)
      // console.log('dayNum',this.formData.dayNum)
      this.formData.dayNumType = '0'
      this.formData.dayTimeType = '1'
    },
    // changeDayNumType(value){
    //   console.log(value)
    //   if(value==1){
    //     this.formData.dayNum=1
    //     this.formData.dayNumType='1'
    //   }
    // },
  },
}
</script>
